<?php

namespace App\Customer\Model;

use App\Facades\JWTAuth;
use EchoPHP\Facades\Redis;
use EchoPHP\Foundation\Exception\HttpException;

class UserAuth {

    //2020-7-7 修改成有效期30分钟并增加有效期5分钟之内刷新authToken
    protected $expireTime = 60 * 30;

    //更新token时间
    protected $updateToken = 60 * 5;

    /**检查登录状态
     * @param $authToken
     * @return array|int
     */
    public function checkLoginSession($authToken) {
        if (empty($authToken)) {
            return -1;
        }

        $loginInfo = JWTAuth::decode($authToken);

        //令牌为空
        if (empty($loginInfo) || !isset($loginInfo['accesskey']) || $loginInfo['accesskey'] == '') {
            return -2;
        }

        //有效期为空
        if (!isset($loginInfo['logintime'])) {
            return -3;
        }

        //超过有效期限制
        if (time() - $loginInfo['logintime'] > $this->expireTime) {
            return -4;
        }

        //用户token在有效期并且超过5分钟则重新刷新token
        $token = '';
        if(time() - $loginInfo['logintime'] > $this->updateToken) {
            $loginInfo['logintime'] = time();
            $token = JWTAuth::encode($loginInfo, $this->expireTime);
        }

//        @2020.7.6 去除redis存储逻辑 防止以后再用 代码片暂时保留
//        $redisKey = $this->getLoginSession($loginInfo['hruid']);
//
//        if ($redisKey != $authToken) {
//            return -5;
//        }

        return array($loginInfo,$token);
    }

    /**保存登录状态
     * @param $hruid
     * @param $loginInfo
     * @return string
     */
    public function setLoginSession($hruid, $loginInfo) {
        $authToken = JWTAuth::encode($loginInfo, $this->expireTime);

//      @2020.7.6 去除redis存储逻辑 防止以后再用 代码片暂时保留
//        $redisObj = Redis::connect('login_session');
//
//        @$redisObj->set('ehiresession:' . $hruid, $authToken, $this->expireTime);
        return $authToken;
    }


    /**删除登录状态
     * @param $hruid
     * @return int
     */
    public function delLoginSession($hruid) {
        $redisObj = Redis::connect('login_session');
        $result = @$redisObj->del('ehiresession:' . $hruid);
        return $result;
    }

    /**查询登录状态
     * @param $hruid
     * @return bool|mixed|string
     */
    public function getLoginSession($hruid) {
        $redisObj = Redis::connect('login_session');
        $authToken = @$redisObj->get('ehiresession:' . $hruid);
        return $authToken;
    }
}